package com.future.account.controller;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 账号信息控制器
 *
 * @author shiyong
 * 2021/5/24 10:49
 */
@RestController
@RequestMapping("/accountInfo")
public class AccountInfoController {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/addAccount")
    public String addAccount(String account) {

        // 创建账号
        // ......

        // 调用邮件服务接口，将账号信息通过邮件发送给客户
        // 获取邮件服务实例列表
        List<ServiceInstance> instanceList = discoveryClient.getInstances("emailService");

        // 选择一个实例，并调用其邮件发送接口
        ServiceInstance serviceInstance = instanceList.get(0);// 选择第一个实例
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        String url = "http://" + host + ":" + port + "/email/emailInfo/sendEmail";
        System.out.println("邮件服务url：" + url);

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("email", "tom@163.com");
        String result = restTemplate.postForObject(url, map, String.class);

        System.out.println("账号信息已发送至" + result);

        return account;
    }

    @PostMapping("/editAccount")
    public String editAccount(String account, HttpServletRequest request) {
        // 返回端口号，测试负载均衡
        int port = request.getServerPort();

        return account + "，端口：" + port;
    }

    @PostMapping("/resetPassword")
    public String resetPassword(String password) {
        // 重置密码
        // ......

        // 发送重置后的密码给用户
        String url = "http://emailService/email/emailInfo/sendEmail";
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("email", "tom@163.com");
        String result = restTemplate.postForObject(url, map, String.class);
        System.out.println("密码已发送至:" + result);

        return password;
    }
}
